package com.xiaoyi.ui.fragment.music;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xiaoyi.App;
import com.xiaoyi.adapter.SaveListAdapter;
import com.xiaoyi.entity.XyData;
import com.xiaoyi.entity.XyDataQueryResult;


import com.xiaoyi.tool.AvBaseTool;
import com.xiaoyi.tool.http.XyApi;
import com.xiaoyi.ui.activity.MusicPlayActivity;
import com.xiaoyi.ui.fragment.base.BaseMainFragment;
import com.xiaoyi.ui.view.DefineLoadMoreView;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import me.yokeyword.fragmentation.anim.DefaultNoAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import com.avin.yi.R;


public class MusicDetailFragment extends BaseMainFragment {
    private static final String ARG_MENU = "arg_menu";
    private SwipeRefreshLayout swipRefreshdata;
    private SwipeMenuRecyclerView dataRecyclerview;
    private SaveListAdapter adapter;
    private TextView typeShowTv;

    private String mMenu;

    public static MusicDetailFragment newInstance(String menu) {

        Bundle args = new Bundle();
        args.putString(ARG_MENU, menu);

        MusicDetailFragment fragment = new MusicDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args != null) {
            mMenu = args.getString(ARG_MENU);
        }
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultNoAnimator();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        typeShowTv = view.findViewById(R.id.typeShowTv);

        swipRefreshdata = view.findViewById(R.id.swipRefreshdata);
        // 刷新监听。
        swipRefreshdata.setOnRefreshListener(mRefreshListener);

        dataRecyclerview = view.findViewById(R.id.dataRecyclerview);
        dataRecyclerview.setSwipeItemClickListener(swipeItemClickListener);
        dataRecyclerview.setLayoutManager(new GridLayoutManager(_mActivity, 4));
        /// dataRecyclerview.addItemDecoration(new DefaultItemDecoration(Color.GRAY));
        adapter = new SaveListAdapter(_mActivity);
        dataRecyclerview.setAdapter(adapter);

        // FooterView。
        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(_mActivity);
        dataRecyclerview.addFooterView(loadMoreView);
        // 设置为加载更多控件
        dataRecyclerview.setLoadMoreView(loadMoreView);
        dataRecyclerview.setLoadMoreListener(mLoadMoreListener);


        loadData("音乐" , mMenu, true);

    }

    private void loadData(String type, String mDir, final boolean isFirstRequst) {

        showLoadDialog2(_mActivity);
        XyApi.getInstance(_mActivity).getDataByTypeAndDir(new SingleObserver<XyDataQueryResult>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onSuccess(XyDataQueryResult XyDataPagerQueryResult) {
                updateData(XyDataPagerQueryResult, isFirstRequst);
                hideLoadDialog2();

            }

            @Override
            public void onError(Throwable e) {
                hideLoadDialog2();
                AvBaseTool.showMsg(_mActivity ,"错误："+ e.getMessage());
            }
        }, type, mDir ,100, currentPageNum, false);

    }


    private int currentPageNum = 1;
    private List<XyData> mDataList = new ArrayList<>();
    private boolean isAllLoaded = false;

    /**
     * 更新数据
     */
    private void updateData(XyDataQueryResult result, boolean isFirstRequst) {
        if (isFirstRequst) {
            mDataList.clear();
            List<XyData> list = result.getList();
            mDataList = list;
            adapter.notifyDataSetChanged(mDataList);
            swipRefreshdata.setRefreshing(false);
             /*
             第一次加载数据：一定要掉用这个方法。.
             第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
             第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
             */
            dataRecyclerview.loadMoreFinish(false, true);
        } else {
            List<XyData> list = result.getList();
            mDataList.addAll(list);
            adapter.notifyItemRangeInserted(mDataList.size() - list.size(), list.size());

            /*
            数据完更多数据，一定要掉用这个方法。
             第一个参数：表示此次数据是否为空。
             第二个参数：表示是否还有更多数据。
             */
            dataRecyclerview.loadMoreFinish(false, true);
            // 如果加载失败调用下面的方法，传入errorCode和errorMessage。
            // errorCode随便传，你自定义LoadMoreView时可以根据errorCode判断错误类型。
            // errorMessage是会显示到loadMoreView上的，用户可以看到。
            // mRecyclerView.loadMoreError(0, "请求网络失败");*/
        }
        typeShowTv.setText(mMenu + ":" + mDataList.size() + " /" + result.getSum());
        deepClone(mDataList);
        isAllLoaded = mDataList.size() >= result.getSum();
    }


    /**
     * 深度克隆保存到全局变量中
     */
    public   void deepClone(List<XyData> list){
        App.musicList.clear();
        for(XyData music : list){
            App.musicList.add( (XyData)music.clone()) ;
        }
    }





    /**
     * 刷新。
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            currentPageNum = 1;
            loadData("音乐"  ,mMenu ,true);

        }
    };

    /**
     * 加载更多。
     */
    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            if (!isAllLoaded) {
                currentPageNum++;
                loadData("音乐"  ,mMenu ,false);
            } else {
                // 数据完更多数据，一定要掉用这个方法。
                // 第一个参数：表示此次数据是否为空。
                // 第二个参数：表示是否还有更多数据。
                dataRecyclerview.loadMoreFinish(false, false);
            }

        }
    };

    private SwipeItemClickListener swipeItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {

            MusicPlayActivity.startInceTance(_mActivity ,position) ;


        }
    };


    @Override
    public boolean onBackPressedSupport() {
        return super.onBackPressedSupport();
    }
}
